package com.servlet;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * Created by Wuxiang on 2018/4/9
 *
 * Servlet 装载过程
 * 1. 构造函数    （一次）
 * 2. init()方法 （一次）
 * 3. 对应的doget dopost方法
 *
 * Servlet 销毁 ：destroy()方法
 *
 * Servlet 配置了 load-on-startup 标签后，会在服务器启动时，装载Servlet，执行 1,2，有具体请求执行 3
 * 不配置的话，当有具体请求时，才装载Servlet，执行 1,2,3
 */
public class TestServlet1 extends HttpServlet {

    /**
     * Constructor of the object.
     */
    public TestServlet1() {
        System.out.println("TestServlet1构造方法被执行....");
    }

    /**
     * Destruction of the servlet. <br>
     */
    public void destroy() {
        System.out.println("TestServlet1销毁方法被执行....");
    }

    /**
     * The doGet method of the servlet. <br>
     *
     * This method is called when a form has its tag value method equals to get.
     *
     * @param request the request send by the client to the server
     * @param response the response send by the server to the client
     * @throws ServletException if an error occurred
     * @throws IOException if an error occurred
     */
    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        System.out.println("TestServlet1的doGet()方法被执行...");
        response.setContentType("text/html;charset=utf-8");
        PrintWriter out = response.getWriter();
        out.println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">");
        out.println("<HTML>");
        out.println("  <HEAD><TITLE>A Servlet</TITLE></HEAD>");
        out.println("  <BODY>");
        out.println("<h1>大家好，我是TestServlet1！</h1>");
        out.println("  </BODY>");
        out.println("</HTML>");
        out.flush();
        out.close();
    }

    /**
     * The doPost method of the servlet. <br>
     *
     * This method is called when a form has its tag value method equals to post.
     *
     * @param request the request send by the client to the server
     * @param response the response send by the server to the client
     * @throws ServletException if an error occurred
     * @throws IOException if an error occurred
     */
    public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        System.out.println("TestServlet1的doPost()方法被执行...");
        doGet(request,response); //让doPost()执行与doGet()相同的操作。
    }

    /**
     * Initialization of the servlet. <br>
     *
     * @throws ServletException if an error occurs
     */
    public void init() throws ServletException {
        // Put your code here
        System.out.println("TestServlet1的初始化方法被执行....");
    }
}
